<template>
     <el-button
                class="ml-3"
                type="primary"
                size="default"
                @click="downloadFile(props.url)"
              >
                <el-icon><Download /></el-icon>
                下载模板文件
              </el-button>
</template>

<script setup lang="ts">
import fileApi from "@/apis/fileApi";

interface Props {
  url: string; // 上传接口地址
}

const props = withDefaults(defineProps<Props>(), {});

/**
 * 下载文件到本地，并根据文件原始的名称及扩展名进行命名
 * @param url 文件下载地址
 */
async function downloadFile(url: string): Promise<void> {
  try {
    await fileApi.getFiles(url).then((response) => {
      const contentType = response.headers["content-type"];
      const contentDisposition = response.headers["content-disposition"];
      // 解析文件名
      let fileName = parseFileName(contentDisposition);

      // 创建 Blob 对象并触发下载
      const blob = new Blob([response.data], { type: contentType });
      triggerFileDownload(blob, fileName);
    });
  } catch (error) {
    console.error("文件下载失败:", error);
    throw error;
  }
}

// 解析文件名（从 Content-Disposition 获取）
function parseFileName(contentDisposition: string): string {
  // 默认文件名
  let fileName = "downloaded-file";
  // 从 Content-Disposition 解析
  if (contentDisposition) {
    const filenameRegex = /filename\*?=([^;]+)/gi;
    let matches: RegExpExecArray | null;
    let decodedFileName: string | null = null;

    while ((matches = filenameRegex.exec(contentDisposition)) !== null) {
      const part = matches[1].trim();

      if (matches[0].toLowerCase().startsWith("filename*=")) {
        // 处理带编码的文件名
        decodedFileName = decodeURIComponent(part.split("'").pop() || "");
      } else {
        // 处理普通文件名（去除引号）
        decodedFileName = part.replace(/^"(.*)"$/, "$1");
      }
    }

    if (decodedFileName) fileName = decodedFileName;
  }
  return fileName;
}

// 触发浏览器下载
function triggerFileDownload(blob: Blob, fileName: string): void {
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement("a");

  link.href = url;
  link.setAttribute("download", fileName);
  document.body.appendChild(link);
  link.click();

  // 清理资源
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url);
}

</script>

<style scoped>

</style>